const soap = require('soap');

// SOAP 服务URL
const SOAP_URL = 'http://szlzhkj.x3322.net:21211/wsdl/IFMCommonAPI';

// 基本认证信息
const baseAuth = {
    UserCode_: '123',
    UserPassword_: '1234'
};

// 创建一个 SOAP 客户端
async function createSoapClient() {
    return new Promise((resolve, reject) => {
        soap.createClient(SOAP_URL, (err, client) => {
            if (err) {
                reject(err);
                return;
            }
            // 输出所有可用的 SOAP 方法名称，用于调试
            console.log('可用的 SOAP 方法:', Object.keys(client).filter(key => typeof client[key] === 'function'));
            resolve(client);
        });
    });
}

// 查找与指定关键词相关的方法
function findRelatedMethods(client, keywords) {
    const availableMethods = Object.keys(client).filter(key => typeof client[key] === 'function');
    
    return availableMethods.filter(method => {
        const methodLower = method.toLowerCase();
        return keywords.some(keyword => methodLower.includes(keyword.toLowerCase()));
    });
}

// 解析 SOAP 响应
function parseSoapResponse(soapResult) {
    try {
        // 检查返回结果格式
        if (soapResult && soapResult.return && soapResult.return.$value) {
            // 尝试解析 SOAP 返回的 JSON 字符串
            const jsonStr = soapResult.return.$value;
            console.log('解析SOAP返回值:', jsonStr);
            
            // 处理空数组的情况
            if (jsonStr === '[]') {
                console.log('SOAP返回了空数组');
                return { success: true, data: [] };
            }
            
            const data = JSON.parse(jsonStr);
            return { success: true, data };
        } else {
            // 直接返回原始结果
            console.log('SOAP返回格式不包含$value, 使用原始结果');
            return { success: true, data: soapResult };
        }
    } catch (error) {
        console.error('解析 SOAP 响应失败:', error);
        return { success: false, error: '解析响应数据失败' };
    }
}

// 尝试调用匹配的方法
async function tryCallMethod(client, methodNames, args) {
    // 首先尝试从我们定义的方法名称列表中查找
    for (const methodName of methodNames) {
        if (typeof client[methodName] === 'function') {
            console.log(`使用方法: ${methodName}，参数:`, args);
            return new Promise((resolve, reject) => {
                client[methodName](args, (err, result) => {
                    if (err) {
                        console.error(`调用方法 ${methodName} 失败:`, err);
                        reject(err);
                        return;
                    }
                    // 记录返回值结构
                    console.log(`方法 ${methodName} 返回值类型:`, typeof result);
                    console.log(`方法 ${methodName} 返回值结构:`, Object.keys(result));
                    if (result && result.return) {
                        console.log(`方法 ${methodName} return字段类型:`, typeof result.return);
                        if (typeof result.return.$value === 'string') {
                            console.log(`方法 ${methodName} $value内容:`, result.return.$value);
                        }
                    } else {
                        console.log(`方法 ${methodName} 返回值不包含return字段`);
                    }
                    resolve(result);
                });
            });
        }
    }
    
    // 如果没找到，尝试寻找相关方法
    const relatedMethods = findRelatedMethods(client, methodNames.map(m => m.replace(/^Get(EQ)?/, '')));
    
    if (relatedMethods.length > 0) {
        const method = relatedMethods[0];
        console.log(`尝试使用相关方法: ${method}`);
        return new Promise((resolve, reject) => {
            client[method](args, (err, result) => {
                if (err) {
                    console.error(`调用方法 ${method} 失败:`, err);
                    reject(err);
                    return;
                }
                // 记录返回值结构
                console.log(`方法 ${method} 返回值类型:`, typeof result);
                console.log(`方法 ${method} 返回值结构:`, Object.keys(result));
                if (result && result.return) {
                    console.log(`方法 ${method} return字段类型:`, typeof result.return);
                    if (result.return.$value) {
                        console.log(`方法 ${method} $value开头:`, result.return.$value.substring(0, 100) + '...');
                    }
                }
                resolve(result);
            });
        });
    }
    
    throw new Error(`找不到匹配的SOAP方法，可用方法: ${Object.keys(client).filter(key => typeof client[key] === 'function').join(', ')}`);
}

// 现金银行明细查询
async function getCashBankDetail(startDate, endDate) {
    try {
        const client = await createSoapClient();
        const args = {
            ...baseAuth,
            StartDate_: startDate,
            EndDate_: endDate
        };
        
        const methodNames = [
            'GetEQCashBankDetail',
            'GetCashBankDetail',
            'getCashBankDetail'
        ];
        
        return await tryCallMethod(client, methodNames, args);
    } catch (error) {
        console.error('现金银行明细查询失败:', error);
        throw error;
    }
}

// 仓库金额明细查询
async function getStoreAmountDetail(startDate, endDate) {
    try {
        const client = await createSoapClient();
        const args = {
            ...baseAuth,
            StartDate_: startDate,
            EndDate_: endDate
        };
        
        const methodNames = [
            'GetEQStoreAmountDetail',
            'GetStoreAmountDetail',
            'GetStockAmountDetail',
            'GetStockDetail',
            'GetEQStockDetail',
            'GetWarehouseAmountDetail',
            'GetInventoryAmountDetail',
            'GetEQInventoryDetail'
        ];
        
        // 查找所有与仓库/库存相关的方法
        console.log('潜在的仓库明细相关方法:', findRelatedMethods(client, ['store', 'stock', 'inventory', 'warehouse', 'detail']));
        
        return await tryCallMethod(client, methodNames, args);
    } catch (error) {
        console.error('仓库金额明细查询失败:', error);
        throw error;
    }
}

// 仓库金额查询
async function getStoreAmount(startDate, endDate) {
    try {
        const client = await createSoapClient();
        const args = {
            ...baseAuth,
            Date_: startDate
        };
        
        const methodNames = [
            'GetEQStoreAmount',
            'GetStoreAmount',
            'GetStockAmount',
            'GetEQStockAmount',
            'GetWarehouseAmount',
            'GetInventoryAmount'
        ];
        
        // 查找所有与仓库/库存相关的方法
        console.log('潜在的仓库金额相关方法:', findRelatedMethods(client, ['store', 'stock', 'inventory', 'warehouse', 'amount']));
        
        return await tryCallMethod(client, methodNames, args);
    } catch (error) {
        console.error('仓库金额查询失败:', error);
        throw error;
    }
}

// 收入金额查询
async function getIncomeAmount(startDate, endDate) {
    try {
        const client = await createSoapClient();
        const args = {
            ...baseAuth,
            StartDate_: startDate,
            EndDate_: endDate
        };
        
        const methodNames = [
            'GetEQIncomeAmount',
            'GetIncomeAmount'
        ];
        
        return await tryCallMethod(client, methodNames, args);
    } catch (error) {
        console.error('收入金额查询失败:', error);
        throw error;
    }
}

// 费用金额查询
async function getFeeAmount(startDate, endDate) {
    try {
        const client = await createSoapClient();
        const args = {
            ...baseAuth,
            StartDate_: startDate,
            EndDate_: endDate
        };
        
        const methodNames = [
            'GetEQFeeAmount',
            'GetFeeAmount'
        ];
        
        return await tryCallMethod(client, methodNames, args);
    } catch (error) {
        console.error('费用金额查询失败:', error);
        throw error;
    }
}

// 公司盈利查询
async function getCompanyProfit(startDate, endDate, company, sales, trader, minNo, no) {
    try {
        const client = await createSoapClient();
        const args = {
            ...baseAuth,
            StartDate_: startDate,
            EndDate_: endDate,
            Company_: company || '',
            Sales_: sales || '',
            Trader_: trader || '',
            MinNo_: minNo || '',
            No_: no || ''
        };
        
        const methodNames = [
            'GetEQCompanyProfit',
            'GetCompanyProfit'
        ];
        
        return await tryCallMethod(client, methodNames, args);
    } catch (error) {
        console.error('公司盈利查询失败:', error);
        throw error;
    }
}

// 盈利明细查询
async function getProfitDetail(startDate, endDate, company, sales, trader, minNo, no) {
    try {
        const client = await createSoapClient();
        const args = {
            ...baseAuth,
            StartDate_: startDate,
            EndDate_: endDate,
            Company_: company || '',
            Sales_: sales || '',
            Trader_: trader || '',
            MinNo_: minNo || '',
            No_: no || ''
        };
        
        const methodNames = [
            'GetEQProfitDetail',
            'GetProfitDetail'
        ];
        
        return await tryCallMethod(client, methodNames, args);
    } catch (error) {
        console.error('盈利明细查询失败:', error);
        throw error;
    }
}

// 销售明细查询
async function getSellDetail(startDate, endDate, company, sales, trader, minNo, no) {
    try {
        const client = await createSoapClient();
        const args = {
            ...baseAuth,
            StartDate_: startDate,
            EndDate_: endDate,
            Company_: company || '',
            Sales_: sales || '',
            Trader_: trader || '',
            MinNo_: minNo || '',
            No_: no || ''
        };
        
        const methodNames = [
            'GetEQSellDetail',
            'GetSellDetail'
        ];
        
        return await tryCallMethod(client, methodNames, args);
    } catch (error) {
        console.error('销售明细查询失败:', error);
        throw error;
    }
}

module.exports = {
    getCashBankDetail,
    getStoreAmountDetail,
    getStoreAmount,
    getIncomeAmount,
    getFeeAmount,
    getCompanyProfit,
    getProfitDetail,
    getSellDetail
}; 